package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)



type CreditCard struct {
	gorm.Model
	Number    string
	UserRefer uint // 新定义的外键名
}



type Product struct {
	gorm.Model
	Code string
	Price uint
}

//1. 定义模型
type User struct {
	gorm.Model
	ID int64
	Name string
	Age byte
}


func Mysqlinit()  (db *gorm.DB) {
	fmt.Print("My init DB")
	dsn := "root:root@tcp(192.168.42.200:3306)/portscan?charset=utf8mb4"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("err")
	}

	return db

}

func My_first_table(db *gorm.DB)  {
	fmt.Println("My_first_table   create table Product ")

	// Migrate the schema
	db.AutoMigrate(&Product{})
	db.Create(&Product{Code: "L1212", Price: 1000})
	// 读取
	var product Product
	db.First(&product, 1) // 查询id为1的product
	product1 := db.First(&product, "code = ?", "L1212") // 查询code为l1212的product
	fmt.Print("My_first_product1\n", product1)

	// 更新 - 更新product的price为2000
	db.Model(&product).Update("Price", 2000)

	// 删除 - 删除product
	//db.Delete(&product)
}

func My_first_table_CreditCard(db *gorm.DB)  {
	fmt.Println("My_first_table   create table Product ")
	// Migrate the schema
	db.AutoMigrate(&CreditCard{})
}



func My_first_table_users(db *gorm.DB)  {
	fmt.Print("create My_first_table_users")
	db.AutoMigrate(&User{})

}

func main() {
// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
//dsn := "user:pass@tcp(192.168.42.200:3306)/portscan?charset=utf8mb4&parseTime=True&loc=Local"
dsn := "root:root@tcp(192.168.42.200:3306)/portscan?charset=utf8mb4"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

if err != nil {
	fmt.Println("err")
}

if db != nil {
	fmt.Println("db")

}
Mydb := Mysqlinit()
My_first_table(Mydb)
My_first_table_users(Mydb)
My_first_table_CreditCard(Mydb)






// returns inserted data's primary key
//result.Error        // returns error
//result.RowsAffected //
}



